package zhoug.common.utils;

import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Editable;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import zhoug.logging.Logger;

/**
 * @Author 35574
 * @Date 2021/7/28
 * @Description
 */
public class TextUtils {
    private static final String TAG = ">>>TextUtils";
    private static final boolean DEBUG = false;
    private static final char CHINESE_UNICODE_START = '\u4E00';
    private static final char CHINESE_UNICODE_END = '\u9FA5';

    /**
     * 获取到输入的值(默认去掉2端的空格) 为空则返回null
     *
     * @param textView
     * @return
     * @see #getTextOrNull(TextView, boolean)
     */
    public static String getTextOrNull(TextView textView) {
        return getTextOrNull(textView, true);
    }

    /**
     * 获取到输入的值 为空则返回null
     *
     * @param textView
     * @param trim     是否去掉前后空格
     * @return
     */
    public static String getTextOrNull(TextView textView, boolean trim) {
        if (textView == null || textView.getText() == null) return null;
        String s = textView.getText().toString();
        if (trim) {
            s = s.trim();
        }
        if (android.text.TextUtils.isEmpty(s)) {
            return null;
        }
        return s;
    }

    /**
     * 字符串转化成int数据
     *
     * @param text
     * @return
     */
    public static int parseInt(String text, int def) {
        if (StringUtils.isNullOrEmpty(text)) {
            return def;
        }
        try {
            return Integer.parseInt(text);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return def;
    }

    /**
     * 字符串转化成long数据
     *
     * @param text
     * @return
     */
    public static long parseLong(String text, long def) {
        if (StringUtils.isNullOrEmpty(text)) {
            return def;
        }
        try {
            return Long.parseLong(text);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return def;
    }

    /**
     * 字符串转化成short数据
     *
     * @param text
     * @return
     */
    public static short parseShort(String text, short def) {
        if (StringUtils.isNullOrEmpty(text)) {
            return def;
        }
        try {
            return Short.parseShort(text);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return def;
    }

    /**
     * 字符串转化成float数据
     *
     * @param text
     * @return
     */
    public static float parseFloat(String text, float def) {
        if (StringUtils.isNullOrEmpty(text)) {
            return def;
        }
        try {
            return Float.parseFloat(text);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return def;
    }

    /**
     * 字符串转化成double数据
     *
     * @param text
     * @return
     */
    public static double parseDouble(String text, double def) {
        if (StringUtils.isNullOrEmpty(text)) {
            return def;
        }
        try {
            return Double.parseDouble(text);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return def;
    }


    /**
     * 给定最大宽度,计算出文字的最佳大小(刚好显示全部文字)
     *
     * @param textSize 默认文字大小
     * @param maxWidth 文字的最大宽度
     * @param text     文本
     * @param paint    画笔
     * @return
     */
    public static float ensureTextSize(float textSize, int maxWidth, String text, Paint paint) {
        if (paint == null) {
            paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        }
        paint.setTextSize(textSize);
        float textWidth = paint.measureText(text);
        if (textWidth > maxWidth) {
            return ensureTextSizeSmall(textSize, maxWidth, text, paint);
        } else if (textWidth < maxWidth) {
            return ensureTextSizeBigger(textSize, maxWidth, text, paint);
        }
        return textSize;
    }


    /**
     * 测量能够完全显示全部文字时的文字大小
     *
     * @param textSize 默认文字大小
     * @param maxWidth 最大宽度
     * @param text     文字
     * @param paint    画笔
     * @return <=textSize
     */
    private static float ensureTextSizeSmall(float textSize, int maxWidth, String text, Paint paint) {
        if (paint == null) {
            paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        }
        paint.setTextSize(textSize);
        float textWidth = paint.measureText(text);
        if (textWidth > maxWidth) {
            textSize -= 2;
            return ensureTextSizeSmall(textSize, maxWidth, text, paint);
        }
        if (DEBUG) {
            Logger.d(TAG, "ensureTextSizeSmall:textSize=" + textSize);
        }
        return textSize;
    }


    /**
     * @param textSize 默认文字大小
     * @param maxWidth 最大宽度
     * @param text     文字
     * @param paint    画笔
     * @return >=textSize
     */
    private static float ensureTextSizeBigger(float textSize, int maxWidth, String text, Paint paint) {
        if (paint == null) {
            paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        }
        paint.setTextSize(textSize);
        float textWidth = paint.measureText(text);
        if (textWidth < maxWidth) {
            textSize += 2;
            return ensureTextSizeBigger(textSize, maxWidth, text, paint);
        }
        textSize -= 2;
        if (DEBUG) {
            Logger.d(TAG, "ensureTextSizeBigger:textSize=" + textSize);
        }
        return textSize;
    }

    /**
     * 包含中文
     *
     * @param str
     */
    public static boolean containsChinese(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        for (char c : str.toCharArray()) {
            if (c >= CHINESE_UNICODE_START && c <= CHINESE_UNICODE_END) {
                return true;// 有一个中文字符就返回
            }
        }
        return false;
    }


    /**
     * 点击图标改变密码显示状态
     *
     * @param btnView      显示/赢藏密码图标ImageVIew
     * @param pwdEditText  密码 EditText
     * @param pwdCloseIcon 隐藏密码时的图标
     * @param pwdOpenIcon  显示密码时的图标
     */
    public static void setChangePwdTransformation(ImageView btnView, EditText pwdEditText,
                                                  @DrawableRes int pwdCloseIcon, @DrawableRes int pwdOpenIcon) {
        if (btnView == null || pwdEditText == null) return;
        btnView.setClickable(true);
        btnView.setOnClickListener(v -> {
            TransformationMethod transformationMethod = pwdEditText.getTransformationMethod();
            if (transformationMethod instanceof HideReturnsTransformationMethod) {
                //隐藏密码
                btnView.setImageResource(pwdCloseIcon);
                pwdEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
            } else if (transformationMethod instanceof PasswordTransformationMethod) {
                //显示密码
                btnView.setImageResource(pwdOpenIcon);
                pwdEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            }
            Editable text = pwdEditText.getText();
            if (text != null) {
                String s = text.toString();
                if (!s.isEmpty()) {
                    pwdEditText.setSelection(s.length());
                }
            }
        });


    }

    /**
     * 设置光标样式
     * @param editText
     * @param cursorDrawableRes
     */
    public static void setTextCursorDrawable(@NonNull TextView editText, @DrawableRes int cursorDrawableRes) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            editText.setTextCursorDrawable(cursorDrawableRes);
        } else {
            try {
                ReflectUtils.setDeclaredField(TextView.class, "mCursorDrawableRes", editText, cursorDrawableRes);
            } catch (Exception e) {
//            e.printStackTrace();
            }
        }
    }

    /**
     * 设置光标样式
     * @param editText
     * @param cursorDrawable
     */
    public static void setTextCursorDrawable(@NonNull TextView editText,  Drawable cursorDrawable) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            editText.setTextCursorDrawable(cursorDrawable);
        } else {
            try {
                ReflectUtils.setDeclaredField(TextView.class, "mCursorDrawable", editText, cursorDrawable);
            } catch (Exception e) {
//            e.printStackTrace();
            }
        }
    }

    public static void setMaxLines(TextView textView,int maxLines){
        if(textView==null)return;
        if (maxLines > 0) {
            textView.setMaxLines(maxLines);
            textView.setSingleLine(maxLines == 1);
        }
    }

}
